import CryptoJS from 'crypto-js/crypto-js'

// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse('qazWSXRFVtgb1234'); //""中与后台一样  密码
const IV = CryptoJS.enc.Utf8.parse('UJMyhntgbVFR4321');  //""中与后台一样

/**
 * AES加密 ：字符串 key iv  返回base64
 * @return {string}
 */
function encrypt(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  //编码 key  //编码iv
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  //编码data
  let data = CryptoJS.enc.Utf8.parse(word);
  // 加密模式为CBC，补码方式为NoPadding
  let encrypted = CryptoJS.AES.encrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  // console.log("加密后的数据:",CryptoJS.enc.Base64.stringify(encrypted.ciphertext))
  //返回base64
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

/**
 * AES 解密 ：字符串 key iv  返回base64
 *
 * @return {string}
 */
function decrypt(word, keyStr, ivStr) {
  let key = KEY
  let iv = IV

  //编码 key  //编码iv
  if (keyStr) {
    key = CryptoJS.enc.Utf8.parse(keyStr);
    iv = CryptoJS.enc.Utf8.parse(ivStr);
  }

  //Base64编码
  const base64 = CryptoJS.enc.Base64.parse(word);
  const base64Str = CryptoJS.enc.Base64.stringify(base64);
  const decrypt = CryptoJS.AES.decrypt(base64Str, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
  console.log("解密后的数据:",decryptedStr.toString())
  return decryptedStr.toString();

}

export default {
  encrypt,
  decrypt
}
